package utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.ToString;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Map;
import java.util.Optional;

public class ServletUtils {

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return RequestContextHolder.getRequestContext();
    }

    @SuppressWarnings("unchecked")
    @SneakyThrows
    public static PageDTO getPageVO() {
        HttpServletRequest request = getRequest();
        PageDTO pageDTO = new PageDTO();
        Optional.ofNullable(request.getParameter("pageNum")).ifPresent(i -> pageDTO.setPageNum(Integer.parseInt(i)));
        Optional.ofNullable(request.getParameter("pageSize")).ifPresent(i -> pageDTO.setPageSize(Integer.parseInt(i)));
        if (request.getMethod().equals("POST")) {
            StringBuilder jsonInput = new StringBuilder();
            String line;
            try (BufferedReader reader = request.getReader()) {
                while ((line = reader.readLine()) != null) {
                    jsonInput.append(line);
                }
            }
            if (StrUtil.isNotBlank(jsonInput.toString())) {
                pageDTO.setQuery(JSONUtil.toBean(jsonInput.toString(), Map.class));
            }
        }
        return pageDTO;
    }

    @Data
    @ToString
    public static class PageDTO {
        private Integer pageNum;
        private Integer pageSize;
        private Map<String, Object> query;

        public PageDTO() {
            this.pageNum = 1;
            this.pageSize = 10;
            this.query = null;
        }

        public <T> T getQueryObj(Class<T> clazz) {
            return JSONUtil.toBean(JSONUtil.toJsonStr(query), clazz);
        }
    }
}
